<?php

namespace Beerus\Modules\Designer\Actions\SaleSend;

use Doraemon\model\Member;
use Encore\Admin\Widgets\StepForm;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class Info extends StepForm
{
    public $title = "选择发送人信息";

    const DESIGNER_PERSON = 1;
    const DESIGNER_IN_PERSON = 2;
    const DESIGNER_ORG = 3;
    const DESIGNER_COMPANY = 4;

    const SEND_TEMPLATE = [
        1 => '设计师个人',
        2 => '设计机构',
        3 => '设计师在职个人',
        4 => '装修公司'
    ];

    public function handle(Request $request)
    {
        $all = $request->all();
        $uid = $all['to_uid'];
        $nick = $all['nick'];

        try {
            $this->checkRule($uid, $nick);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return $this->prev()->with(compact('error'));
        }

        return $this->next($request->all());
    }

    public function form()
    {
        $this->radio('type', '发送的模板')->options(self::SEND_TEMPLATE)->required('不能为空');
        $this->text('to_uid', '用户UID')->setWidth(4, 2)->required('不能为空')->help("只支持填写一个");
        $this->text('nick', '用户昵称')->setWidth(4, 2)->required('不能为空')->help("只支持填写一个");
    }

    public function checkRule($uid, $nick)
    {
        $user = Member::getUserInfoNew($uid);
        if (!$user) {
            throw new \Exception("用户信息错误");
        }
        if ($user['nick'] != $nick) {
            throw new \Exception("你输入的UID和昵称不符，请检查");
        }
        if (in_array($user['type'], [Member::AUTH_USER_DESIGNER, Member::AUTH_DECO_COMPANY])) {
            throw new \Exception("该用户当前已认证，若用户需要变更身份请联系对接运营");
        }
        return true;
    }
}